package io.iec.edp.caf.commons.runtime.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

class MsuConfigReader {

    //序列化工具
    private static ObjectMapper objectMapper = new ObjectMapper();

    private static Log log = LogFactory.getLog(MsuConfigReader.class);

    /**
     * 读取文本文件内容
     *
     * @param filePath
     * @return
     * @throws IOException
     */
    static String readToBuffer(String filePath) {
        StringBuffer buffer = new StringBuffer();
        try {
            InputStream stream = null;
            BufferedReader reader = null;
            try {
                File file = new File(filePath);
                if (!file.exists())
                    return null;
                stream = new FileInputStream(file);
                String line; // 用来保存每行读取的内容
                reader = new BufferedReader(new InputStreamReader(stream, StandardCharsets.UTF_8));
                line = reader.readLine(); // 读取第一行
                while (line != null) { // 如果 line 为空说明读完了
                    buffer.append(line); // 将读到的内容添加到 buffer 中
                    buffer.append("\n"); // 添加换行符
                    line = reader.readLine(); // 读取下一行
                }
            } finally {
                if (reader != null)
                    reader.close();
                if (stream != null)
                    stream.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return buffer.toString();
    }

    /**
     * 从ServiceUnit.json中读取su
     * @param jsonString
     * @return
     */
    static String getSuFromJson(String jsonString){
        String result = null;
        try{
            String jsonStrTmp = jsonString.substring(jsonString.indexOf(":") + 1, jsonString.lastIndexOf("}"));
            if(jsonStrTmp==null||jsonStrTmp.length()==0){
                throw new RuntimeException("A ServiceUnit.json has no content.");
            }
            Map<String,Object> map = objectMapper.readValue(jsonStrTmp, Map.class);
            if(map.containsKey(MsuConfigVariable.SU_JSON_SU_NAME)){
                result = (String) map.get(MsuConfigVariable.SU_JSON_SU_NAME);
            }
        }catch(Throwable e){
            log.error("Get Su from ServiceUnit.json error, content is: "
                    +jsonString+" failed reason: "+ e.getMessage());
        }finally {
            return result;
        }
    }

    /**
     * @param content caf_serviceunit.json文件内容
     * @param allSu 环境中所有su(包括未启用的)
     */
    static public List<String> getEnableSuListFromJson(String content, List<String> allSu){
        List<String> enableSuList = new ArrayList<>();
        //没有su信息则为空
        if(allSu == null) return enableSuList;

        //json配置是否为黑白名单
        boolean isBlackList = true;
        if (content==null||"".equals(content)) {
            log.error("Caf_ServiceUnit.json has no content");
        }
        try{
            //caf_serviceunit.json中的su信息列表
            List<Map<String,Object>> suList = new ArrayList<>();
            //序列化文件
            Map<String,Object> deployConfig = objectMapper.readValue(content,Map.class);
            if(deployConfig==null){
                throw new RuntimeException("Can't read Caf_ServiceUnit.json");
            }
            //获取配置类对象
            Map<String,Object> deploymentConfiguration = (Map)deployConfig.get(MsuConfigVariable.CAF_JSON);

            if(deployConfig.containsKey(MsuConfigVariable.CAF_JSON_STRATEGY)){
                isBlackList = (boolean)deployConfig.get(MsuConfigVariable.CAF_JSON_STRATEGY);
            }
            //获取su信息列表
            suList = (List)deploymentConfiguration.get(MsuConfigVariable.CAF_JSON_SU);

            //获取启用列表和禁用列表
            List<String> disableSu = new ArrayList<>();
            List<String> ableSu = new ArrayList<>();

            suList.forEach(su->{
                if(su.containsKey(MsuConfigVariable.CAF_JSON_SU_NAME)&&su.containsKey(MsuConfigVariable.CAF_JSON_SU_ENABLE))
                    if((boolean)su.get(MsuConfigVariable.CAF_JSON_SU_ENABLE)){
                        ableSu.add((String)su.get(MsuConfigVariable.CAF_JSON_SU_NAME));
                    }else{
                        disableSu.add((String) su.get(MsuConfigVariable.CAF_JSON_SU_NAME));
                    }
            });
            if(isBlackList){
                //黑名单则将su信息列表中的被禁用的su，从全部列表中去除
                allSu.forEach(su->{
                    if(!disableSu.contains(su)) enableSuList.add(su);
                });
            }else{
                //白名单则只保存su信息列表中启用的su，并验证是否在全部列表中
                ableSu.forEach(su->{
                    if(allSu.contains(su)) enableSuList.add(su);
                });
            }


        }catch (Exception e){
            log.error("Get info from Caf_ServiceUnit.json error,error reason: "+ e.getMessage()
                    +" Caf_ServiceUnit.json info :\n" + content);
        }finally {
            return enableSuList;
        }

    }
}
